<script setup lang="ts">
  import { ref, onMounted,useTemplateRef } from 'vue'
  import * as d3 from "d3";
  import GenerateCoor from '../unitls/generate.js';

  const mainDom = useTemplateRef('mainDom');
  const createD3 = async () => {

    const width = 1920;
    const height = 800;
    const marginTop = 20;
    const marginRight = 20;
    const marginBottom = 30;
    const marginLeft = 40;

    const nodes = await d3.csv("../../dataBase/export.csv");
    const linkDatas = await d3.json("../../dataBase/link.json");
    const links = linkDatas.links;


    const yearList = nodes.map(item=>item.year);
    const startShowTime = '2024-11-19';
    const endShowTime = (Number(d3.min(yearList))-3) + '-01-01';
    console.log(endShowTime,startShowTime);
    // const links = 
   
    // Declare the x (horizontal position) scale.
    const xScale = d3.scaleUtc()
        .domain([new Date(endShowTime),new Date(startShowTime)])
        .range([marginLeft, width - marginRight]);

    //获取x坐标位置。
    nodes.map(item=>{
      item.x = xScale(new Date(item.year+'-01-01'));
    })

    const generateor = new GenerateCoor({
      maxHeight:800,
      yValue:100,
      nodes,
      k:0.2,
      stepCoff:0.5,
    });

    const showNodes = generateor.movePoint(0);
    console.log(nodes,showNodes);
    
    let mapids = {
    }

    showNodes.map(item=>{
      mapids[item.id] = item.y;
    })

    console.log('mapids',mapids)

    links.map(item=>{
      item[0].y = mapids[item[0].id]
      item[1].y = mapids[item[1].id]
    })

    console.log('links----------',links)

    // Declare the y (vertical position) scale.
    const yScale = d3.scaleLinear()
        .domain([0, 100])
        .range([height - marginBottom, marginTop]);

    const svg = d3.create("svg")
        .attr("width", width)
        .attr("height", height);


    // Add the x-axis.
    const axis_x = svg.append("g")
        .attr("transform", `translate(0,${height - marginBottom})`)
        .call(d3.axisBottom(xScale).ticks(50))



    const axis_ticks = svg.append("g")
          .attr("transform", `translate(0,${height - marginBottom})`)
          .call(d3.axisTop(xScale).tickValues([new Date('1921-07-01'),new Date("1949-10-01"),new Date('1992-08-07')])
                .tickSize(height - marginTop - marginBottom).tickFormat(getTickValue))
          .call(g => g.selectAll(".tick line")
              .attr("stroke-opacity", 0.5)
              .attr("stroke-dasharray", "2,2"))
          .call(g => g.selectAll(".tick text")
              .attr("x", 45)
              .attr("dy", 15))
          .select(".domain").remove();

        axis_x.select(".domain")
        .attr('stroke-width','5')
        .attr('stroke-dasharray','10,2')
        .attr('stroke','red');

        axis_x.selectAll(".tick line").remove();


    // Add the y-axis.
    svg.append("g")
        .attr("transform", `translate(${marginLeft},0)`)
        .call(d3.axisLeft(yScale));


    // 创建线生成器
    // const line = d3.line()
    //   .x(d => xScale(d.fx))
    //   .y(d => yScale(d.fy));

    // 绘制连线
    // svg.append('path')
    //   .datum(nodes)
    //   .attr('d', line)
    //   .attr('stroke', 'steelblue')
    //   .attr('stroke-width', 2)
    //   .attr('fill', 'none');
     svg.append("g").selectAll('line')
        .data(links)
        .enter()
        .append('line')
        .attr('x1',d => xScale(new Date(d[0].year+'-01-01')))
        .attr('y1',d => yScale(d[0].y))
        .attr('x2',d => xScale(new Date(d[1].year+'-01-01')))
        .attr('y2',d => yScale(d[1].y))
        .attr('stroke', '#ff7982')
        .attr('fill-opacity',0.08)
        .attr('stroke-width', 1)

    const nodeEvent =  svg.append("g").selectAll("g")
      .data(showNodes)
      .enter()
      .append('g');

      nodeEvent.append('circle')
      .attr('cx', d => xScale(new Date(d.year+'-01-01')))
      .attr('cy', d => yScale(d.y))
      .attr('r', d => d.important == '是' ? 40 : 30)
      .attr('fill',d => d.important == '是' ? '#e62e3b' : '#ff7982')
      .attr('fill-opacity',0.9)
      .on('click',function(e){
        console.log(e.target.__data__)
      });

      nodeEvent.append('text')
      .attr('x',d => xScale(new Date(d.year+'-01-01')) - 15)
      .attr('y',d => yScale(d.y) - 15)
      .style('font-size','12px')
      .style('fill','#ffffff')
      .html((d)=>{
        let textLength = d.name.length;
        if(textLength <= 4){
          return `<tspan dx="-9" dy="18">${d.name}</tspan>`
        }else if(textLength <= 16){
          return `<tspan dx="-10" dy="10">${d.name.slice(0,4)}</tspan>
                  <tspan dx="-53" dy="18">${d.name.slice(4)}</tspan>`
        }else if(textLength <= 26){
          return `<tspan dx="-10" dy="-5">${d.name.slice(0,4)}</tspan>
                  <tspan dx="-14" dy="0">${d.name.slice(4,10)}</tspan>
                  <tspan dx="-10" dy="5">${d.name.slice(10)}</tspan>`
        }else{
          return `<tspan dx="-5" dy="-12">${d.name.slice(0,4)}</tspan>
                  <tspan dx="-10" dy="-5">${d.name.slice(4,10)}</tspan>
                  <tspan dx="-10" dy="5">${d.name.slice(10,16)}</tspan>
                  <tspan dx="-5" dy="12">${d.name.slice(16)}</tspan>`
        }
      })
      // .append((d)=>[document.createElement("tspan"),document.createElement("tspan")])
      // .append('tspan')
      // .text(d => d.name);

    return svg;
  }

  const getTickValue = () => {
    return "年月日发生的事情";
  }

  const formatBottomTick = (e) => {
    console.log(e.getYear())
    return e.getYear();
  }

  onMounted(async ()=>{
    const svgDom = await createD3();
    mainDom.value.append(svgDom.node());
    // debugger;
  })
</script>

<template>
  <main ref="mainDom" style="text-align:center;background-color:#FFEDEA">
  </main>
</template>
<style>
svg circle {
  cursor: pointer;
  transition: r 0.5s ease-in-out;
}
svg circle:hover{
  r:50
}
svg text{
  pointer-events: none;
}
</style>
